package util;

import java.security.MessageDigest;

/**
 *
 * @author Giang Nguyen
 */
public class CryptoUtil {

    public static byte[] encryptString(String str, String salt) throws Exception {
        MessageDigest md = null;
        md = MessageDigest.getInstance("SHA-1");
        md.reset();
        md.update(salt.getBytes());
        return md.digest(str.getBytes());
    }

    public static String convertToHex(byte[] data) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
        	int halfbyte = (data[i] >>> 4) & 0x0F;
        	int two_halfs = 0;
        	do {
	        	if ((0 <= halfbyte) && (halfbyte <= 9))
	                buf.append((char) ('0' + halfbyte));
	            else
	            	buf.append((char) ('a' + (halfbyte - 10)));
	        	halfbyte = data[i] & 0x0F;
        	} while(two_halfs++ < 1);
        }
        return buf.toString();
    }

    public static String encryptPasswordToHex(String password, String salt) throws Exception {
        return convertToHex(encryptString(password, salt));
    }

    public static String getRandowmPassword(int length) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int nextChar = (int) (Math.random() * 62);
            if (nextChar < 10) { // 0-9
                stringBuffer.append(nextChar);
                //System.out.println(nextChar);
            }
            else if (nextChar < 36) { // a-z
                stringBuffer.append((char)(nextChar - 10 + 'a'));
                //System.out.println((char)(nextChar - 10 + 'a') + "-" + nextChar);
            }
            else {
                stringBuffer.append((char)(nextChar - 36 + 'A'));
                //System.out.println((char)(nextChar - 36 + 'A') + "-" + nextChar);
            }
        }
        return stringBuffer.toString();
    }
    
}
